//
//  MineViewController.swift
//  WeChatDemo
//
//  Created by YJH on 2025/5/6.
//

import UIKit
import SnapKit

struct MineItem{
    let mineName: String
    let imageName: String
}

struct MineModel {
    let items : [MineItem]
    init() {
        self.items = [
            .init(mineName: "服务", imageName: "star.fill"),
            .init(mineName: "收藏", imageName: "bookmark.fill"),
            .init(mineName: "朋友圈", imageName: "person.3.fill"),
            .init(mineName: "卡包", imageName: "wallet.pass.fill"),
            .init(mineName: "表情", imageName: "face.smiling.fill"),
            .init(mineName: "设置", imageName: "gearshape.fill")
        ]
    }
}

class MineViewController: UIViewController {
    let data = MineModel()
    
    var isMinorModeOn = false
    
    lazy var tableView: UITableView = {
        let tableView = UITableView(frame: .zero, style: .grouped)
        tableView.register(MineTableViewCell.self, forCellReuseIdentifier: "cell")
        tableView.rowHeight = 44
        tableView.dataSource = self
        tableView.delegate = self
        tableView.sectionHeaderHeight = 20
        tableView.sectionFooterHeight = 30
        tableView.tableHeaderView = headerView
        return tableView
    }()
    
    lazy var headerView: UIView = {
        let view = MineHeaderView()
        view.thumbnail.image = UIImage(systemName: "pencil.tip.crop.circle.fill")
        view.nameLabel.text = "心飞翔"
        view.detailLabel.text = "微信号：xianghjwsldf"
        view.frame = CGRect(origin: .zero, size: .init(width: 100, height: 100))
        return view
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupViews()
        
        NotificationCenter.default.addObserver(self, selector: #selector(handle(notification:)), name: .didMinorModeChange, object: nil)
    }
    private func setupViews() {
        view.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
    }
    
    @objc private func handle(notification: Notification) {
        if let info = notification.object as? [String: Bool], let isOn = info["isOn"] {
            isMinorModeOn = isOn
            tableView.reloadData()
        }
    }
    
}

// MARK: - table view data source
// 实现 UITableViewDataSource 和 UITableViewDelegate 协议方法
extension MineViewController: UITableViewDataSource, UITableViewDelegate {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        3
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0 {
            return 1
        } else if section == 1 {
            return 4
        } else if section == 2 {
            return 1
        }
        
        return data.items.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        guard let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as? MineTableViewCell
        else {
            return .init()
        }
        var item: MineItem
        if indexPath.section == 0, let model = data.items[safe: indexPath.row] {
            item = model
        } else if indexPath.section == 1, let model = data.items[safe: indexPath.row + 1] {
            item = model
        } else if indexPath.section == 2, let model = data.items[safe: indexPath.row + 5] {
            item = model
        } else {
            item = data.items[0] // 避免意外情况
        }
        cell.mineName.text = item.mineName
        if let image = UIImage(systemName: item.imageName) {
            cell.imageView?.image = image
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        var selectedItem: MineItem
        if indexPath.section == 0 {
            selectedItem = data.items[indexPath.row]
        } else if indexPath.section == 1 {
            selectedItem = data.items[indexPath.row + 1]
        } else if indexPath.section == 2 {
            selectedItem = data.items[indexPath.row + 5]
        } else {
            selectedItem = data.items[0] // 避免意外情况
        }
        
        if selectedItem.mineName == "设置" {
            let detailVC = SetViewController()
            detailVC.selectedMineItem = selectedItem
            detailVC.callBack = {
                tableView.reloadData()
            }
            navigationController?.pushViewController(detailVC, animated: true)
        } else {
            print("点击了 \(selectedItem.mineName)，但不进行页面跳转")
        }
        tableView.deselectRow(at: indexPath, animated: true)
        tableView.reloadData()
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        0.01
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        if section == 2 {
            return 30
        }
        return 5
    }
    
    func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? {
        if section == 2 {
            return "未成年模式：" + "\(isMinorModeOn)"
        }
        return ""
    }
    
}

class MineTableViewCell: UITableViewCell {
    
    lazy var mineName: UILabel = {
        let label = UILabel()
        label.textColor = .darkGray
        label.font = .systemFont(ofSize: 14, weight: .medium)
        return label
    }()
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        setupViews()
        accessoryType = .disclosureIndicator
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupViews() {
        contentView.addSubview(mineName)
        mineName.snp.makeConstraints { make in
            make.centerY.equalTo(contentView)
            make.left.equalTo(imageView!.snp.right).offset(8)
        }
    }
}

class MineHeaderView: UIView {
    
    lazy var thumbnail: UIImageView = {
        let imageView = UIImageView()
        return imageView
    }()
    
    lazy var nameLabel: UILabel = {
        let label = UILabel()
        label.font = .systemFont(ofSize: 16, weight: .medium)
        return label
    }()
    
    lazy var detailLabel: UILabel = {
        let label = UILabel()
        label.font = .systemFont(ofSize: 14, weight: .regular)
        return label
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupViews()
    }
    
    @MainActor required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupViews() {
        addSubview(thumbnail)
        thumbnail.snp.makeConstraints { make in
            make.centerY.equalToSuperview()
            make.width.height.equalTo(60)
            make.left.equalToSuperview().offset(20)
        }
        
        addSubview(nameLabel)
        nameLabel.snp.makeConstraints { make in
            make.left.equalTo(thumbnail.snp.right).offset(20)
            make.top.equalTo(thumbnail.snp.top).offset(5)
        }
        
        addSubview(detailLabel)
        detailLabel.snp.makeConstraints { make in
            make.left.equalTo(thumbnail.snp.right).offset(20)
            make.bottom.equalTo(thumbnail.snp.bottom).inset(5)
        }
    }
    
}
